<template>
  <div id="teacherNumByAgePage">
    <div ref="chartRef" style="width: 800px; height: 600px"></div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch } from 'vue'
import * as echarts from 'echarts'
import { getNumByAgeUsingGet } from '@/api/teacherController.ts'
import { message } from 'ant-design-vue'

const chartRef = ref(null)
let chartInstance = null

const ageData = ref()

const renderChart = () => {
  if (!chartInstance) {
    chartInstance = echarts.init(chartRef.value)
  }

  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow',
      },
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true,
    },
    xAxis: [
      {
        type: 'category',
        data: ['20以下', '20-29', '30-39', '40-49', '50及以上'],
        axisTick: {
          alignWithLabel: true,
        },
      },
    ],
    yAxis: [
      {
        type: 'value',
      },
    ],
    series: [
      {
        name: '人数',
        type: 'bar',
        barWidth: '60%',
        data: [
          ageData.value['20以下'],
          ageData.value['20-29'],
          ageData.value['30-39'],
          ageData.value['40-49'],
          ageData.value['50及以上'],
        ],
      },
    ],
  }

  chartInstance.setOption(option)
}

onMounted(async () => {
  const res = await getNumByAgeUsingGet()
  if (res.data.code === 0 && res.data.data) {
    ageData.value = res.data.data
  } else {
    message.error('获取数据失败' + res.data.message)
  }
  // 监听窗口大小变化，防止图表不自适应
  window.addEventListener('resize', () => {
    chartInstance.resize()
  })
})

// 如果ageData是接口动态获取的，推荐监听它重新渲染
watch(ageData, () => {
  renderChart()
})
</script>

<style scoped>
#teacherNumByAgePage {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
}
</style>
